package edu.zut.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @WebServlet : 代替web.xml中的映射配置
 * name:servlet-name
 * value: 当前servlet的访问路劲 == urlPatterns
 */
@WebServlet(name = "ShowTimeServlet", value = "/lastTime")
public class ShowTimeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //记录展示用户访问当前应用的上次时间
        //先获取当前请求所携带的所有cookie
        Cookie[] cookies = request.getCookies();
        //表示记录上次访问时间的cookie是否存在
        boolean flag = true;
        //判断cookies是否为空
        if (cookies != null && cookies.length != 0) {
            //遍历cookie数组
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastTime")) {
                    //获取上次保存的访问时间并做更新
                    String lastTime = cookie.getValue();
                    lastTime = URLDecoder.decode(lastTime,"utf-8");
                    System.out.println("上次访问时间 = " + lastTime);
                    response.getWriter().write("上次访问时间 = " + lastTime);
                    Date date = new Date();
                    lastTime = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss").format(date);
                    lastTime = URLEncoder.encode(lastTime,"utf-8");
                    //重新保存时间
                    cookie.setValue(lastTime);
                    //设置cookie的生命周期
                    cookie.setMaxAge(24*60*60);
                    //将当前cookie返回给浏览器
                    response.addCookie(cookie);
                    flag = false;
                }
            }
        }
        if (cookies == null || cookies.length == 0 || flag) {
            //第一次新建cookie
            Date date = new Date();
            String lastTime = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss").format(date);
            response.getWriter().write("当前访问时间：" + lastTime);
            //编码
            lastTime = URLEncoder.encode(lastTime,"utf-8");
            Cookie cookie = new Cookie("lastTime", lastTime);
            //设置cookie的生命周期
            cookie.setMaxAge(24*60*60);
//            cookie.setPath("/user/*");
            //将cookie响应给浏览器
            response.addCookie(cookie);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
